import Fetch from "./request";

const appId = "107781815";
const appSecret =
  "d84d3dbe3a34b3a51b5d5d3594f6213c1e396f4bd6c58fe389cf76f50e4ea995";
const scope = "openid profile email";
export const baseUrl = "https://oauth-login.cloud.huawei.com/oauth2/v3";
export const redirectUrl = "http://127.0.0.1:5500/index.html";
export const oauthUrl = `${baseUrl}/authorize?client_id=${appId}&client_secret=${appSecret}&response_type=code&scope=${scope}&redirect_uri=${redirectUrl}&access_type=offline`;
export const logoutUrl = `https://oauth-login.cloud.huawei.com/connect/v2/logout?response_type=token&client_id=${appId}&next=${redirectUrl}`;

export const appIdYellow = "xyl";
export const appSecretYellow = "xyl.huawei.com";
export const scopeYellow = "base.profile";
export const redirectUrlYellow = "http://localhost.huawei.com:5500/index.html";
export const baseUrlYellow = "https://uniportal.huawei.com/saaslogin1/oauth2";
// export const oauthUrlYellow = `${baseUrlYellow}/authorize?client_id=${appIdYellow}&response_type=code&scope=${scopeYellow}&redirect_uri=${redirectUrlYellow}`
export const oauthUrlYellow = `https://login.huawei.com/login?redirect=${redirectUrlYellow}`;

export const fetchToken = (data: string) => {
  let code = data;
  code = code.substring(data.indexOf("?code="));
  code = code.substring(6);
  if (!code) return Promise.reject();
  return Fetch.post(
    `${baseUrl}/token`,
    {
      grant_type: "authorization_code",
      code,
      client_id: appId,
      client_secret: appSecret,
      redirect_uri: redirectUrl,
    },
    "application/x-www-form-urlencoded;charset=utf-8;"
  );
};

export const fetchTokenYellow = (data: string) => {
  let code = data;
  code = code.substring(data.indexOf("?code="));
  code = code.substring(6, code.indexOf("&"));
  if (!code) return Promise.reject();
  return Fetch.post(
    `${baseUrlYellow}/accesstoken`,
    JSON.stringify({
      grant_type: "authorization_code",
      code,
      client_id: appIdYellow,
      client_secret: appSecretYellow,
      redirect_uri: redirectUrlYellow,
    }),
    "application/json;charset=utf-8;"
  );
};

export const fetchRefreshToken = (token: string) => {
  return Fetch.post(
    `${baseUrl}/token`,
    {
      grant_type: "refresh_token",
      refresh_token: encodeURIComponent(token),
      client_id: appId,
      client_secret: appSecret,
      redirect_uri: redirectUrl,
    },
    "application/x-www-form-urlencoded;charset=utf-8;"
  );
};

export const fetchRefreshTokenYellow = (token: string) => {
  return Fetch.post(
    `${baseUrlYellow}/token`,
    {
      grant_type: "refresh_token",
      refresh_token: encodeURIComponent(token),
      client_id: appIdYellow,
      scope: scopeYellow,
    },
    "application/json;charset=utf-8;"
  );
};
